import React from 'react';
import style from './style.objective-item';
import { tip, Loading, Avatar, Menu, IconFont, IconButton, Button, Link, Progress } from 'sq-ui';
import { error, Modal, info, success } from '../../ui-components';
import util from '../../util';
import cx from 'classnames';
import ObjectiveRelative from './ObjectiveRelative';
import ObjectiveNote, { pageSize as commentsPageSize } from './ObjectiveNote';
import { checkCurrentAmount } from './Objective';
import { Motion, spring, presets } from 'react-motion';
import { NextGuide } from '../guide/Guide';
import TodoList from './TodoList';

const IMAGES_PATH = process.env.NODE_ENV === 'production'? './static/images': './static/src/images'

const TipIconButton = tip(IconButton);

export default
class ObjectiveItem extends React.Component {

  state = {
    deleteObjective: false,
    deleteKeyResult: false,
    deleteItem: false,
    kr: null,
    todos: [],
  };

  static contextTypes = {
    router: React.PropTypes.object
  }

  fetchObjectiveRelative() {
    const { objectiveId, actions } = this.props;
    actions.fetchObjectiveAncester(objectiveId);
    actions.fetchObjectiveChildren(objectiveId);
  }

  resetObjectiveRelative() {
    const { objectiveId, actions } = this.props;
    actions.resetObjectiveRelative();
  }

  deleteObjective() {
    info('删除中...');
    this.props.actions.deleteObjective(this.props.objectiveId, () => {
      if (this.props.editObjectiveDetail) {
        const { query } = this.props.location;
        this.context.router.replace({
          query,
          pathname: `/okr/${this.props.objectivePeriodId}/objectives`,
        });
      } else {
        this.props.fetchObjective(null, true);
      }
      success('删除成功!');
    });
    this.cancelDeleteItem();
  }

  deleteKeyResult() {
    info('删除中...');
    this.props.actions.deleteKeyResult(this.state.kr.keyResultId, () => {
      success('删除成功!');
      if (this.props.editObjectiveDetail) {
        this.props.refreshKeyResult();
      } else {
        this.props.fetchObjective();
      }
    });
    this.cancelDeleteItem();
  }

  componentWillUnmount() {
    this.unmount = true;
  }

  cancelDeleteItem() {
    this.setState({
      deleteItem: false,
    }, () => {
      setTimeout(() => {
        if (this.unmount) return;
        this.setState({
          deleteObjective: false,
          deleteKeyResult: false,
          kr: null
        });
      }, 200)
    })
  }

  requestDeleteObjective() {
    this.setState({
      deleteItem: true,
      deleteObjective: true
    })
  }

  requestDeleteKeyResult(kr) {
    this.setState({
      deleteItem: true,
      deleteKeyResult: true,
      kr,
    })
  }

  isNull() {
    return this.props.editObjectiveDetail && util.isNull(this.props.obj);
  }

  type(props) {
    return (props || this.props).location.query.type;
  }

  renderContent() {
    if (this.isNull()) return null;
    const {
      progressMetricType,
      content,
      currentAmount,
      startingAmount,
      goalAmount,
      unit,
      progress,
      deadline,
      directorList,
      objectiveEditable,
      priority,
      isPrivate,
      objectiveId,
      isAutoCalc,
      editObjectiveDetail,
      canDrag,
      dragItem,
    } = this.props;
    // 部件
    // return null;
    const parts = {
      progress: <Progress
                key={objectiveId}
                circle
                r={25}
                border={3}
                value={progress* 100}
                colors={["#f4f5f8", "#7fd7af"]}
                labelAnimation
              />,
      actions: <div className={style.actions}></div>,
      others: <div className={style.others}>
                <p>
                  <label>进度:</label>
                  {
                    isAutoCalc
                      ?<span>自动计算</span>
                      :<span>{progressMetricType == 1? `${currentAmount}%`: `${currentAmount}/${goalAmount}${unit}（初始值：${startingAmount}）`}</span>
                  }
                </p>
                <p>
                  <label>优先级:</label>
                  <span className={cx(style['key-result-priority'], style['key-result-priority-' + priority])}>
                    <span>
                      {
                        priority == 0? '极高': priority == 1? '高': priority == 2? '中': '低'
                      }
                    </span>
                  </span>
                </p>
                {
                  deadline?
                  <p>
                    <label>截止日:</label>
                    <span>{util.time(deadline, '/')}</span>
                  </p>: null
                }
                {
                  !util.isNull(directorList) ?
                    <ul className={style['director-list']}>
                      {
                        directorList.map((obj, i) => (
                          <li key={i}>
                            <Link to={`/okr/objective-targetAll?userId=${obj.coreUserProfileVO.userId}`} target="_blank">
                              <span>
                                <Avatar src={obj.coreUserProfileVO.avatarUrl} width={18}/>
                                <span>{obj.coreUserProfileVO.fullName}</span>
                              </span>
                            </Link>
                          </li>
                        ))
                      }
                    </ul>: null
                }
                </div>
    };
    return (
      <div className={style.content}>
        <div>
          <div className={style['top-wrapper']}>
            <div className={style['left-wrapper']}>
              {canDrag && objectiveEditable ? dragItem : null}
              { parts.progress }
              <div className={style.info}>
                {
                  editObjectiveDetail ? (
                    <span className={style.title}>{content}</span>
                  ) : (
                    <span>
                      <Link
                        className={style.title}
                        to={`/okr/objectives/${this.props.objectiveId}?${util.body(this.props.location.query)}`}
                        label={content}
                      />
                      <span style={{marginLeft: "12px"}}>挑战度: { this.props.challenge ? this.props.challenge : "暂无"}</span>
                    </span>
                  )
                }
                {parts.lock}
              </div>
            </div>
            { parts.actions }
          </div>
          { parts.others }
        </div>
      </div>
    );

    return editObjectiveDetail ? (
      <div className={style.content}>
        <div>
          <div className={style['top-wrapper']}>
            <div className={style['left-wrapper']}>
              { parts.progress }
              <div className={style.info}>
                <span className={style.title}>{content}</span>
                {parts.lock}
              </div>
            </div>
            { parts.actions }
          </div>
          { parts.others }
        </div>
      </div>
    ) : (
      <div className={style.content}>
        <div className={style['left-wrapper']}>
          { parts.progress }
          <div className={style.info}>
            <span className={style['link-wrapper']}>
              <span>
                <Link
                  className={style.title}
                  to={`/okr/objectives/${this.props.objectiveId}?${util.body(this.props.location.query)}`}
                  label={content}
                />
                { parts.lock }
              </span>
            </span>
            { parts.others }
          </div>
        </div>
        { parts.actions }
      </div>
    )
  }

  renderKeyResultList() {
    if (this.isNull()) return null;
    const { keyResultList, objectiveEditable, objectiveCreatable, thumbup = null } = this.props;
    let thumpBupKeyResultVOs = thumbup ? thumbup.thumpBupKeyResultVOs : null;
    return (
      <div style={{position: 'relative'}}>
        {
          !util.isNull(keyResultList)?
            <div className={style['key-result-wrapper']}>
              {
                keyResultList.map((kr, i) => (
                  <div key={kr.keyResultId}>
                    <div className={cx(style['key-result'])}>
                      <div className={cx(style['floor1'])}>
                        <IconFont size="20" className={style.icon} value="target" />
                        <p className={style['kr-content']}>{ kr.content }</p>
                        <span className={cx(style['key-result-priority'], style['key-result-priority-' + kr.priority])}>
                          <span>
                            {
                              kr.priority == 0? '极高': kr.priority == 1? '高': kr.priority == 2? '中': '低'
                            }
                          </span>
                        </span>
                        {
                          kr.deadline?
                          <p className={style.deadline}>
                            <label>截止日:</label>
                            <span>{util.time(kr.deadline, '/')}</span>
                          </p>: <p className={style.deadline} />
                        }
                        <Progress
                          className={style['kr-progress']+'  '+(kr.audit !== 2 ? style['kr-progress-notAudit'] : "")}
                          line
                          width={120}
                          height={8}
                          value={kr.progress* 100}
                          label={kr.progressMetricType != 1? v => `${kr.currentAmount}/${kr.goalAmount}${kr.unit}（初始值：${kr.startingAmount}）`: null}
                          labelAnimation
                        />
                        {
                          !util.isNull(kr.directorList)? (
                            <span className={style['kr-directors']}>
                              {
                                kr.directorList.slice(0, 3).map((v, i) => {
                                  const { coreUserProfileVO: u } = v;
                                  if (i == kr.directorList.slice(0, 3).length-1) {
                                    return <Link target="_blank" key={i} label={`${u.fullName} `} to={`/okr/objective-targetAll?userId=${u.userId}`} />;
                                  }
                                  return <Link target="_blank" key={i} label={`${u.fullName}、`} to={`/okr/objective-targetAll?userId=${u.userId}`} />;
                                })
                              }
                              {
                                kr.directorList.length > 3?
                                <span>等人</span>: null
                              }
                            </span>
                          ): null
                        }
                        {
                            thumpBupKeyResultVOs ? this.renderKrEdit(kr, thumpBupKeyResultVOs[i]) : this.renderKrEdit(kr)
                        }
                      </div>
                      <div className={cx(style['floor2'])}>
                        <div style={{width: "100%"}}>
                          <label style={{paddingLeft: "50px", width: "12%", display: "inline-block", verticalAlign: "top"}}>如何衡量：</label>
                          <p style={{width: "87%",display: "inline-block", verticalAlign: "top", wordWrap: "break-word", wordBreak: "break-all"}}>{kr.why ?  kr.why : "暂无"}</p>
                        </div>
                        <div style={{width: "100%"}}>
                          <label style={{paddingLeft: "50px", width: "12%", display: "inline-block", verticalAlign: "top"}}>创建原因：</label>
                          <p style={{width: "87%",display: "inline-block", verticalAlign: "top", wordWrap: "break-word", wordBreak: "break-all"}}>{kr.howMeasure ? kr.howMeasure : "暂无"}</p>
                        </div>
                      </div>
                    </div>
                    {
                      (!this.props.editObjectiveDetail && this.state.todos.some(t => t.keyResultId === kr.keyResultId)) ?
                      <div className={style.todoWrapper}>
                        <TodoList
                          keyResultId={kr.keyResultId}
                          fetchTodoList={this.props.actions.fetchTodoList}
                          createTodo={this.props.actions.createTodo}
                          updateTodo={this.props.actions.updateTodo}
                          deleteTodo={this.props.actions.deleteTodo}
                        />
                        <span className={style.closeTodo} onClick={() => {
                          this.setState({
                            todos: this.state.todos.filter(t => t.keyResultId !== kr.keyResultId)
                          });
                        }}>收起</span>
                      </div>
                      : null
                    }
                    {
                      this.props.editObjectiveDetail ? (
                        <TodoList
                          keyResultId={kr.keyResultId}
                          fetchTodoList={this.props.actions.fetchTodoList}
                          createTodo={this.props.actions.createTodo}
                          updateTodo={this.props.actions.updateTodo}
                          deleteTodo={this.props.actions.deleteTodo}
                        />
                      ) : null
                    }
                  </div>
                ))
              }
            </div>: null
        }
        {
          objectiveCreatable?
          <div style={{ position: 'relative' }} className={cx(style['add-keyresult'], {
            [style['no-keyresult']]: util.isNull(keyResultList)
          })}>
            <Button
              blueSimpleLine
              hover
              icon="plus"
              label="添加关键结果"
              onClick={() => {
                util.track.call({mpModule:'目标::关键结果添加编辑弹窗'});
                this.props.requestCreateKeyResult(this.props.objectiveId);
                if (this.props.app.naviStep == 4 && this.props.app.guide == 2 && !this.props.editObjectiveDetail) {
                  this.props.actions.setStepGuide(3);
                }
              }}
            />
            {
              (this.props.index == 0 && this.props.app.naviStep == 4 && this.props.app.guide == 2 && !this.props.editObjectiveDetail) ? (
                <NextGuide
                  right
                  styles={{
                    left: '206px',
                    top: '9px',
                  }}
                  str="点击这里"
                />
              ) : null
            }
          </div>: null
        }
      </div>
    );
  }

  renderKrEdit = (kr, thumpKr) => {
    const { editObjectiveDetail, objectiveDeletable, objectiveEditable } = this.props;
    //if (!objectiveEditable && !objectiveDeletable) return null;
    return (
      <div className={style['kr-edit']}>
        {
          thumpKr ?
            <div
              onClick={() => {
                if(this.props.likeKeyResult) this.props.likeKeyResult(kr);
              }}
              className={style["kr-like"]+" "+style[thumpKr.isThumpBup == 0 ? "kr-islike": "kr-notlike"]}
            >
              <img className={style["kr-like-icon"]} src={`${util.getImagePath()}/default/kr-like.png`} alt=""/>
              <img className={style["kr-islike-icon"]} src={`${util.getImagePath()}/default/kr-islike.png`} alt=""/>
              <span>{thumpKr.total}</span>
            </div> : null
        }
        <IconButton
          style={{ cursor: 'pointer' }}
          size="16"
          icon="todo"
          className={style['kr-log']}
          style={{marginRight: '5px', cursor: 'pointer'}}
          onClick={() => this.setState({
            todos: [
              ...this.state.todos,
              kr,
            ]
          })}
        />
        {
          this.props.editReamrk === "false" ? null :
          <Menu>
            <IconButton
              style={{ cursor: 'pointer' }}
              size="16"
              icon="chat"
              className={style['kr-log']}
            />
            <ObjectiveNote
              {...kr}
              // editObjectiveDetail={this.props.editObjectiveDetail}
              // actions={this.props.actions}
              // fetchObjective={this.props.fetchObjective}
              // refreshKeyResult={this.props.refreshKeyResult}
              {...this.props}
            />
          </Menu>
        }
        {
          objectiveEditable?
          <IconButton
            icon="modify"
            size="16"
            onClick={() => {
              util.track.call({mpModule:'目标::关键结果添加编辑弹窗'});
              this.props.editKeyResult(kr)
            }}
          />: null
        }
      </div>
    );
  }

  renderEdit() {
    if (this.isNull()) return null;
    const { objectiveDeletable, objectiveEditable, thumbup = null } = this.props;
    //if (!objectiveEditable && !objectiveDeletable) return null;
    return (
      <div className={style.edit}>
        {
          thumbup ?
            <div
              onClick={e => {
                if(this.props.likeObjective) this.props.likeObjective()
              }}
              className={style["objective-like"]+" "+style[thumbup.isThumpBup == 0 ? "objective-islike" : "objective-notlike"]}
            >
              <div className={style["toolTip"]}>点赞</div>
              <img className={style["like-icon"]} src={`${util.getImagePath()}/default/like.png`} alt=""/>
              <img className={style["islike-icon"]} src={`${util.getImagePath()}/default/islike.png`} alt=""/>
              <img className={style["likehover-icon"]} src={`${util.getImagePath()}/default/likehover.png`} alt=""/>
              <img className={style["islikehover-icon"]} src={`${util.getImagePath()}/default/islikehover.png`} alt=""/>
              <p>{thumbup.total}</p>
            </div> : null
        }
        {
          this.props.editObjectiveDetail ? null : (
            <Menu
              onClose={() => {
                this.resetObjectiveRelative.call(this);
                if (!this.props.editObjectiveDetail && this.props.app.naviStep === 7 && this.props.app.guide == 3) {
                  this.props.actions.setStepGuide(1);
                }
              }}
              onOpen={() => {
                this.resetObjectiveRelative();
                this.fetchObjectiveRelative();
              }}
            >
              <TipIconButton
                top
                tip="相关目标"
                size="16"
                icon="tree"
                style={{ transform: 'rotate(90deg)' }}
                onClick={() => {
                  if (!this.props.editObjectiveDetail && this.props.app.naviStep === 7 && this.props.app.guide == 2) {
                    this.props.actions.setStepGuide(3);
                  }
                }}
              />
              <ObjectiveRelative
                editObjective={this.props.editObjective}
                editable={objectiveEditable}
                content={this.props.content}
                okr={this.props.okr}
                objectiveId={this.props.objectiveId}
                query={this.props.location.query}
                actions={this.props.actions}
                app={this.props.app}
              />
            </Menu>
          )
        }
        {
          this.props.editReamrk === "false" ? null :
          <Menu
            onClose={() => {
              if (!this.props.editObjectiveDetail && this.props.app.naviStep === 5 && this.props.app.guide == 3) {
                this.props.actions.setStepGuide(1);
              }
            }}
          >
            <TipIconButton
              top
              onClick={() => {
                if (!this.props.editObjectiveDetail && this.props.app.naviStep === 5 && this.props.app.guide == 2) {
                  this.props.actions.setStepGuide(3);
                }
              }}
              tip="批注"
              icon="chat"
              size="16"
              top
            />
            <ObjectiveNote {...this.props}/>
          </Menu>
        }
        {
          objectiveEditable?
          <TipIconButton
            top
            style={{height: "34px"}}
            tip="编辑"
            icon="modify"
            size="16"
            onClick={() => {
              util.track.call({mpModule:'目标::目标添加编辑弹窗'});
              this.props.editObjective();
              if (!this.props.editObjectiveDetail && this.props.app.naviStep === 6 && this.props.app.guide == 2) {
                this.props.actions.setStepGuide(3);
              }
            }}
          />: null
        }
        {
          (this.props.index == 0 && !this.props.editObjectiveDetail && this.props.app.naviStep === 5 && this.props.app.guide == 2) ? (
            <NextGuide
              left
              styles={{
                left: '-140px',
              }}
              str="点击这里"
            />
          ) : null
        }
        {
          (this.props.index == 0 && !this.props.editObjectiveDetail && this.props.app.naviStep === 6 && this.props.app.guide == 2) ? (
            <NextGuide
              left
              styles={{
                left: '-98px',
              }}
              str="点击这里"
            />
          ) : null
        }
        {
          (this.props.index == 0 && !this.props.editObjectiveDetail && this.props.app.naviStep === 7 && this.props.app.guide == 2) ? (
            <NextGuide
              left
              styles={{
                left: '-189px',
              }}
              str="点击这里"
            />
          ) : null
        }
      </div>
    );
  }

  render() {
    let styles = this.props.styles ? {
      ...this.props.styles,
      display: this.props.x > 1000 ? 'none' : 'block',
    } : {};
    if (!this.props.y && !this.props.x) styles = {};
    return (
      <div
        style={styles}
        className={cx(style.root, {
          [style['objective-detail']]: this.props.editObjectiveDetail,
          [style['objective-detail-loading']] : this.isNull(),
          [style['not-editable']]: !this.props.objectiveEditable && !this.props.editable,
        })}
      >
        {
          this.isNull()
            ? <Loading
                style={{
                  position: 'absolute',
                  top: '50%',
                  left: '18px',
                  marginTop: '-12.5px',
                }}
              />
            : null
        }
        <div className={style["objective-main"]}>
          { this.renderContent() }
          { this.renderEdit() }
        </div>
        { this.renderKeyResultList() }
        <Modal
          active={this.state.deleteItem}
          onRequestClose={::this.cancelDeleteItem}
          title={this.state.deleteObjective? "删除目标": '删除关键结果'}
          actions={[
            'cancel',
            () => {
              if (this.state.deleteObjective) {
                this.deleteObjective();
              } else {
                this.deleteKeyResult();
              }
            }
          ]}
        >
          <p>确定{this.state.deleteObjective? "删除目标": '删除关键结果'}吗?</p>
        </Modal>
      </div>
    );
  }
}
